package com.lenovo.newsapp.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.newsapp.R;
import com.lenovo.newsapp.activity.MainActivity;
import com.lenovo.newsapp.activity.NewsDetailImgActivity;
import com.lenovo.newsapp.adapter.NewsListAdapter;
import com.lenovo.newsapp.model.HomeNews;
import com.lenovo.newsapp.parser.InfoJSONParser;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.PreferenceUtil;
import com.lenovo.newsapp.util.ThreadPool;
import com.lenovo.newsapp.view.MyPullToRefreshListView;
import com.lenovo.newsapp.view.MyPullToRefreshListView.OnFooterLoadListener;
import com.lenovo.newsapp.view.MyPullToRefreshListView.OnHeaderLoadListener;

public class MailListFragment extends Fragment implements OnHeaderLoadListener,
		OnFooterLoadListener {
	private ProgressBar progressBar;
	private MyPullToRefreshListView listview;
	private NewsListAdapter myListAdapter;
	private int pageNo;
	boolean success = true;
	boolean canLoadMore = true;
	private final Handler handler = new Handler();
	private ArrayList<HomeNews> resultList = new ArrayList<HomeNews>();
	private ArrayList<HomeNews> newlist = new ArrayList<HomeNews>();
	private MainActivity main;
	private ImageView bigImg;
	View bigPictureView;
	private TextView bigTV;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Const.isFrefresh=true;

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		main = (MainActivity) activity;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if(Const.isFrefresh){
			pageNo = 1;
			loadData(Const.INIT_FLAG);
			Const.isFrefresh=false;
		}
////		if(Const.MAIL_LIST == 0){
//			pageNo = 1;
//			loadData(Const.INIT_FLAG);
////			Const.MAIL_LIST = 1;
////		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.listview_info, container,
				false);
		listview = (MyPullToRefreshListView) rootView
				.findViewById(R.id.listview);
		progressBar = (ProgressBar) rootView
				.findViewById(R.id.loading_progressbar);
		return rootView;
	}

	private void loadMoreListView() {
		myListAdapter.appendOlder(resultList);
		listview.onFooterLoadComplete();
	}

	private void refreshListView() {
		myListAdapter.refreshData(resultList);
		listview.onHeaderLoadComplete();
	}

	@Override
	public void onFooterLoad() {

		if (null != resultList && resultList.size() > 0) {
			pageNo++;
			loadData(Const.LOAD_MORE_FLAG);
		} else {
			Toast.makeText(main, R.string.load_no_more_message,
					Toast.LENGTH_SHORT).show();
			listview.onFooterLoadComplete();
		}
	}

	private void loadData(final int flag) {
//		if (!HttpUtil.isNetworkAvailable(main)) {
//			Toast.makeText(main, R.string.can_not_connect_server,
//					Toast.LENGTH_SHORT).show();
//		}
		if (flag == Const.INIT_FLAG) {
			showLoadProgressBar();
		}
		ThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					try {
						resultList = InfoJSONParser.getInfoList(pageNo, PreferenceUtil.getString("username", ""),flag, main);
						canLoadMore = (resultList.size() == Const.PAGE_SIZE);
						success = true;
					} catch (Exception e) {
						success = false;
						e.printStackTrace();
					}

					handler.post(new Runnable() {

						@Override
						public void run() {
							if (success) {

								switch (flag) {
								case Const.INIT_FLAG:
									setUpListViews();
									break;
								case Const.LOAD_MORE_FLAG:
									loadMoreListView();
									break;
								case Const.REFRESH_FLAG:
									refreshListView();
								default:
									break;
								}

							} else {
								Toast.makeText(main,
										R.string.toast_err_download,
										Toast.LENGTH_SHORT).show();
							}

							listview.onHeaderLoadComplete();
							listview.setCanLoadFooter(canLoadMore);
							hideLoadProgressBar();
						}

					});
				}
			});
	}

	@Override
	public void onHeaderLoad() {
		pageNo = 1;
		loadData(Const.REFRESH_FLAG);
	}

	protected void hideLoadProgressBar() {
		progressBar.setVisibility(View.GONE);
	}

	protected void showLoadProgressBar() {
		progressBar.setVisibility(View.VISIBLE);
	}

	private void setUpListViews() {
		Log.v(Const.DEBUG, "resultList-- " + resultList.size());
		if (null != resultList && resultList.size() > 0) {
			myListAdapter = new NewsListAdapter(main, resultList);
			listview.setAdapter(myListAdapter);
			listview.setOnHeaderLoadListener(this);
			listview.setOnFooterLoadListener(this);
			listOnclicklistener listener = new listOnclicklistener();
			listview.setOnItemClickListener(listener);
		}
	}


	/**
	 * 首页list点击事件，根据类型进入不同页面
	 * 
	 * @author Geoffrey
	 * 
	 */
	class listOnclicklistener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			HomeNews info = (HomeNews) listview.getItemAtPosition(position);
			Intent intent = new Intent(main, NewsDetailImgActivity.class);
			intent.putExtra("id", "" + info.getNewsId());
			startActivity(intent);
		}
	}
}
